var util = require('./util.js');
var app = getApp();
var HOST;

/**
 * get请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Get(params) {
  params = params || {};
  params.method = 'GET';
  _request(params);
}

/**
 * post请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Post(params) {
  params = params || {};
  params.method = 'POST';
  _request(params);
}

/**
 * 异步请求基础方法
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _request(params) {
  var {
    method,
    url,
    data,
    success,
    fail,
    iHandleFail
  } = params;
  //var userSid = app.getUserSid();
  var alias = app.getAlias();
  var employee_sid = app.getEmployeeSid();
  console.log(employee_sid);
  var sid = app.globalData.sid;
  var requestObj;
  var header = {};

  HOST = app.getHost();

  method = (method || 'GET').toLowerCase();
  url;
  // if (employee_sid) {
  //   url += '&employee_sid=' + employee_sid;
  // }
  data = data || {};
  //data.userSid = userSid;
  //data.sid = sid;

  if (method == 'POST') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  }

  //console.log('---req url:', HOST, url);
  requestObj = {
    url: HOST + url,
    header: header,
    method: method,
    success: function (res) {
      var data = res.data;
      typeof success == "function" && success(data);
      //if (data.code == 1) {return false}
      // if (data.code == 1) {
      //   typeof success == "function" && success(data);
      // } else {
      //   //typeof fail == "function" && fail(data);
      //   if (iHandleFail) {
      //     return;
      //   }
      //   if (data.code == 107) {
      //     wx.navigateTo({
      //       url: '/pages/login/index'
      //     });
      //   } else {
      //     if (data.msg) {
      //       util.alert(data.msg);
      //     }
      //   }
      // }
    },
    fail: function (res) {
      // console.log('---req fail:', res);
      typeof fail == "function" && fail(res);
    }
  };

  requestObj.data = data;

  wx.request(requestObj);
}

module.exports = {
  P: _Post,
  G: _Get,
  request: _request
}